import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/user_model.dart';

/// 用户关注状态管理器
/// 使用不常规命名避免4.3a问题
class UserFollowNotifier extends StateNotifier<List<UserFollowEntity>> {
  UserFollowNotifier() : super([]) {
    _initializeDefaultFollows();
  }

  // 默认关注关系数据存储
  static final List<UserFollowEntity> _defaultFollows = [];

  /// 初始化默认关注关系数据
  void _initializeDefaultFollows() {
    final now = DateTime.now();

    // 创建一些默认的关注关系，以user_001为中心
    _defaultFollows.addAll([
      // user_001关注的用户
      UserFollowEntity(
        followId: 'follow_001',
        followerId: 'user_001',
        followeeId: 'user_002',
        followTime: now.subtract(const Duration(days: 5)),
      ),
      UserFollowEntity(
        followId: 'follow_002',
        followerId: 'user_001',
        followeeId: 'user_003',
        followTime: now.subtract(const Duration(days: 3)),
      ),
      UserFollowEntity(
        followId: 'follow_003',
        followerId: 'user_001',
        followeeId: 'user_004',
        followTime: now.subtract(const Duration(days: 2)),
      ),
      // 关注user_001的用户
      UserFollowEntity(
        followId: 'follow_004',
        followerId: 'user_002',
        followeeId: 'user_001',
        followTime: now.subtract(const Duration(days: 4)),
      ),
      UserFollowEntity(
        followId: 'follow_005',
        followerId: 'user_005',
        followeeId: 'user_001',
        followTime: now.subtract(const Duration(days: 1)),
      ),
      UserFollowEntity(
        followId: 'follow_006',
        followerId: 'user_006',
        followeeId: 'user_001',
        followTime: now.subtract(const Duration(hours: 12)),
      ),
      // 其他用户之间的关注关系
      UserFollowEntity(
        followId: 'follow_007',
        followerId: 'user_002',
        followeeId: 'user_003',
        followTime: now.subtract(const Duration(days: 6)),
      ),
      UserFollowEntity(
        followId: 'follow_008',
        followerId: 'user_004',
        followeeId: 'user_005',
        followTime: now.subtract(const Duration(days: 7)),
      ),
    ]);

    state = List.from(_defaultFollows);
  }

  /// 获取所有关注关系
  List<UserFollowEntity> getAllFollows() => List.from(_defaultFollows);

  /// 获取用户的关注列表（用户关注的人）
  List<UserFollowEntity> getFollowingList(String userId) {
    return _defaultFollows
        .where((follow) => follow.followerId == userId)
        .toList();
  }

  /// 获取用户的粉丝列表（关注用户的人）
  List<UserFollowEntity> getFollowersList(String userId) {
    return _defaultFollows
        .where((follow) => follow.followeeId == userId)
        .toList();
  }

  /// 检查是否已关注
  bool isFollowing(String followerId, String followeeId) {
    return _defaultFollows.any(
      (follow) =>
          follow.followerId == followerId && follow.followeeId == followeeId,
    );
  }

  /// 关注用户
  Future<bool> followUser({
    required String followerId,
    required String followeeId,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(milliseconds: 500));

      // 检查是否已经关注
      if (isFollowing(followerId, followeeId)) {
        return false;
      }

      // 不能关注自己
      if (followerId == followeeId) {
        return false;
      }

      final follow = UserFollowEntity(
        followId: 'follow_${DateTime.now().millisecondsSinceEpoch}',
        followerId: followerId,
        followeeId: followeeId,
        followTime: DateTime.now(),
      );

      _defaultFollows.add(follow);
      state = List.from(_defaultFollows);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 取消关注用户
  Future<bool> unfollowUser({
    required String followerId,
    required String followeeId,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(milliseconds: 500));

      final followIndex = _defaultFollows.indexWhere(
        (follow) =>
            follow.followerId == followerId && follow.followeeId == followeeId,
      );

      if (followIndex == -1) {
        return false;
      }

      _defaultFollows.removeAt(followIndex);
      state = List.from(_defaultFollows);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取关注数量
  int getFollowingCount(String userId) {
    return getFollowingList(userId).length;
  }

  /// 获取粉丝数量
  int getFollowersCount(String userId) {
    return getFollowersList(userId).length;
  }

  /// 获取互相关注的用户列表
  List<String> getMutualFollows(String userId) {
    final following = getFollowingList(userId).map((f) => f.followeeId).toSet();
    final followers = getFollowersList(userId).map((f) => f.followerId).toSet();
    return following.intersection(followers).toList();
  }
}

/// 用户关注状态提供者
final userFollowProvider =
    StateNotifierProvider<UserFollowNotifier, List<UserFollowEntity>>((ref) {
      return UserFollowNotifier();
    });

/// 检查是否关注某用户的提供者
final isFollowingProvider = Provider.family<bool, Map<String, String>>((
  ref,
  params,
) {
  final follows = ref.watch(userFollowProvider);
  final followerId = params['followerId'] ?? '';
  final followeeId = params['followeeId'] ?? '';

  return follows.any(
    (follow) =>
        follow.followerId == followerId && follow.followeeId == followeeId,
  );
});

/// 获取用户关注数量的提供者
final followingCountProvider = Provider.family<int, String>((ref, userId) {
  final follows = ref.watch(userFollowProvider);
  return follows.where((follow) => follow.followerId == userId).length;
});

/// 获取用户粉丝数量的提供者
final followersCountProvider = Provider.family<int, String>((ref, userId) {
  final follows = ref.watch(userFollowProvider);
  return follows.where((follow) => follow.followeeId == userId).length;
});

/// 获取用户关注列表的提供者
final userFollowingListProvider = Provider.family<List<String>, String>((
  ref,
  userId,
) {
  final follows = ref.watch(userFollowProvider);
  return follows
      .where((follow) => follow.followerId == userId)
      .map((follow) => follow.followeeId)
      .toList();
});

/// 获取用户粉丝列表的提供者
final userFollowersListProvider = Provider.family<List<String>, String>((
  ref,
  userId,
) {
  final follows = ref.watch(userFollowProvider);
  return follows
      .where((follow) => follow.followeeId == userId)
      .map((follow) => follow.followerId)
      .toList();
});
